package com.zndroid.base.model;

import android.os.Build;
import android.widget.Checkable;

import androidx.annotation.Nullable;

import com.chad.library.adapter.base.entity.node.BaseExpandNode;
import com.chad.library.adapter.base.entity.node.BaseNode;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @author lzy
 * @date 2021/5/19
 */
@SuppressWarnings("unused")
public abstract class BaseCheckableNode extends BaseExpandNode implements Checkable {
    protected boolean isChecked = false;
    protected long id = -1;
    protected long parentId = -1;
    protected List<BaseNode> children = new ArrayList<>();

    public BaseCheckableNode() {}

    public BaseCheckableNode(long id, long parentId) {
        this.id = id;
        this.parentId = parentId;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getParentId() {
        return parentId;
    }

    public void setParentId(long parentId) {
        this.parentId = parentId;
    }

    @Override
    public void setChecked(boolean checked) {
        this.isChecked = checked;
    }

    @Override
    public boolean isChecked() {
        if (isNotEmpty(getChildNode())) {
            for (BaseNode node : getChildNode()) {
                if (node instanceof BaseCheckableNode) {
                    if (!((BaseCheckableNode) node).isChecked()) {
                        //如果子集不为空且有一个没选中，则当前都没选中
                        isChecked = false;
                        return false;
                    } else {
                        isChecked = true;
                    }
                }
            }
        }
        return isChecked;
    }

    @Override
    public void toggle() {
        this.isChecked = !this.isChecked;
    }

    private boolean isNotEmpty(Collection<?> collection) {
        return null != collection && !collection.isEmpty();
    }

    @Nullable
    @Override
    public List<BaseNode> getChildNode() {
        return children;
    }

    public void addChild(BaseNode node) {
        children.add(node);
    }

    public void setChildren(List<BaseNode> children) {
        this.children = children;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        BaseCheckableNode that = (BaseCheckableNode) o;
        return id == that.id
                && parentId == that.parentId;
    }

    @Override
    public int hashCode() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            return Objects.hash(id, parentId);
        } else {
            int hash = 5;
            hash = 67 * hash + (int)(this.id ^ (this.id >>> 32)) + (int)(this.parentId ^ (this.parentId >>> 32));
            return hash;
        }
    }
}
